from flask import Blueprint, request, render_template, jsonify, json
from app.models import Role, Auth
from app.forms import AddRoleForm
from app.utils import get_form_input_array
from flask_login import login_required

role_controller = Blueprint("role", __name__)

@role_controller.route("/index")
@login_required
def index():
    return render_template("role/index.html")

@role_controller.route('/lst')
@login_required
def look():
    page = request.args.get('page', 1, type = int)
    limit = request.args.get('limit', 10, type = int)
    keyword = request.args.get('keyword', '', type=str)
    pagination = Role.get_roles_page(keyword, page, limit)
    roles = pagination.items
    return jsonify({"code": 0, "msg": "获取成功", "data": [role.to_json() for role in roles], "count": pagination.total})

@role_controller.route("/add", methods=["GET", "POST"])
@login_required
def add():
    form = AddRoleForm()
    if request.method == "POST":
        if form.validate_on_submit():
            name = form.name.data
            auth_ids = get_form_input_array(request, "auth")
            role = Role(name=name)
            role.auths = Auth.get_auth_by_ids(auth_ids)
            Role.add_role(role)
            return jsonify({"code": 1, "msg": "添加成功"})
        else:
            return jsonify({"code": 0, "msg": "添加失败 - " + str(form.errors)})

    tree = Auth.auth_tree3()
    return render_template("role/add.html", tree = json.dumps(tree), form = form)

@role_controller.route("/edit", methods=["GET", "POST"])
@login_required
def edit():
    id = request.args.get('id', 0, type=int)
    role = Role.get_role_by_id(id)
    form = AddRoleForm()
    if request.method == "POST":
        if form.validate_on_submit():
            name = form.name.data
            auth_ids = get_form_input_array(request, "auth")
            role.name = name
            role.auths = Auth.get_auth_by_ids(auth_ids)
            Role.update_role()
            return jsonify({"code": 1, "msg": "修改成功"})
        else:
            return jsonify({"code": 0, "msg": "修改失败 - " + str(form.errors)})
    
    ids = []
    for auth in role.auths:
        ids.append(auth.id)
    tree = Auth.auth_tree3(ids)
    return render_template("role/edit.html", tree = json.dumps(tree), form = form, role = role)

@role_controller.route("/delete_op", methods=["POST"])
@login_required
def delete_op():
    id = request.form.get("id", 0, type=str).split(",")
    result = Role.delete_role_by_id(id)
    if result == -1:
        return jsonify({"code": 0, "msg": "有管理员，不能删除"})
    return jsonify({"code": 1, "msg": "删除成功"})